import axios from 'axios'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
interface IResponse<T = any> {
  code: number
  msg: string
  data: T
}

export type IRes<T> = Promise<IResponse<T>>

export interface ITask {
  _id: string
  title: string
  description: string
  status: 'pending' | 'done' | 'all'
  created_at: string
  updated_at: string
}

const httpRequest = axios.create({
  baseURL: '/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
})

httpRequest.interceptors.response.use((res) => {
  return res.data
})

const generateTaskApi = () => {
  type ITaskListQuery = Partial<Omit<ITask, 'id'>>
  const getTasks = (query?: ITaskListQuery): IRes<ITask[]> => {
    return httpRequest.get('/tasks/list', { params: query })
  }
  const deleteTask = (id: ITask['_id']): IRes<ITask> => {
    return httpRequest.post(`/tasks/delete_tasks/${id}`)
  }
  const updateTask = (taskInfo: Partial<ITask>): IRes<ITask> => {
    return httpRequest.post(`/tasks/update_task/${taskInfo._id}`, taskInfo)
  }

  return {
    getTasks,
    deleteTask,
    updateTask,
  }
}

const taskApi = generateTaskApi()

export default taskApi
